package com.walle.activityservice.controller;

import com.walle.activityservice.model.BusinessDefine;
import com.walle.activityservice.service.BusinessDefineService;
import com.walle.common.result.ResultResponse;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author zhangjiapeng
 * @Package com.hdai.dps.activiti.controller
 * @Description: ${todo}
 * @date 2018/12/19 16:56
 */
@RestController
@RequestMapping("/activiti")
@Slf4j
public class ActivitiController {


    @Autowired
    private BusinessDefineService businessDefineService;


    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    /**
     * 获取用户任务列表
     * @param userId
     * @return
     */
    @PostMapping("/queryTaskByUser")
    public ResultResponse queryTaskByUser(String userId){
        try {
            List<Task> resultTask = taskService.createTaskQuery().taskCandidateOrAssigned(userId).list();
            List<String> taskIdList = new ArrayList<>();
            for(Task task : resultTask){
                taskIdList.add(task.getProcessInstanceId());
            }
            return ResultResponse.ofSuccess(taskIdList);
        } catch (Exception e) {
            log.error("获取用户任务列表失败:{}",e.getMessage(),e);
            return ResultResponse.ofError(e.getMessage());
        }
    }

    /**
     * 完成任务
     * @param userId 用户Id
     * @param procInstId 流程实例ID
     * @param vars 参数 可为空
     * @return 下一个任务的Id
     */
    @PostMapping("/completeTask")
    public ResultResponse  completeTask(String userId, String procInstId,@RequestBody Map<String,Object> vars){

        try {
            Task task = taskService.createTaskQuery().processInstanceId(procInstId).taskAssignee(userId).singleResult();
            String taskId = task.getId();
            taskService.claim(taskId, userId);
            taskService.complete(taskId, vars);
            Task nextTask =  taskService.createTaskQuery().processInstanceId(procInstId).singleResult();
            String nextTaskId = null;
            if(nextTask != null){
                nextTaskId = nextTask.getId();
            }
            return ResultResponse.ofSuccess(nextTaskId);
        } catch (Exception e) {
            log.error("完成任务失败",e.getMessage(),e);
            return  ResultResponse.ofError(e.getMessage());
        }

    }
    @PostMapping("/getByProcInstIdCode")
    public ResultResponse getByProcInstIdCode( String businessCode,@RequestBody Map<String,Object> vars){

        try {
            BusinessDefine businessDefine = businessDefineService.getByCode(businessCode);
            Assert.notNull(businessDefine,"业务未定义");
            ProcessInstance processInstance = runtimeService.startProcessInstanceById(businessDefine.getProcDefId(),vars);
            return ResultResponse.ofSuccess(processInstance.getId());
        } catch (Exception e) {
            log.error("根据业务代码创建业务实例失败：{}",e.getMessage());
            return  ResultResponse.ofError(e.getMessage());
        }

    }
    @PostMapping("/getTaskDefinitionKey")
    ResultResponse getTaskDefinitionKey(@RequestParam("procInstId") String procInstId){
        try {
            Task task = taskService.createTaskQuery().processInstanceId(procInstId).singleResult();
            Assert.notNull(task,"无法获取任务信息");
            return ResultResponse.ofSuccess(task.getTaskDefinitionKey());
        } catch (Exception e) {
            log.error("获取流程当前节点定义名称失败",e.getMessage(),e);
            return ResultResponse.ofError(e.getMessage());
        }
    }
}
